<?php

namespace app\controllers;


use Yii;
use yii\base\DynamicModel;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use zonday\weixin\api;

class TemplateController extends BaseController
{
    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionSetIndustry()
    {
        $request = Yii::$app->getRequest();
        if ($request->isAjax && $industry = $request->post('industry')) {
            $templateApi = new api\Template();
            $data = [
                "industry_id1" => $industry[0],
                "industry_id2" => $industry[1],
            ];
            $templateApi->apiSetIndustry($data);
            return new Response([
                'format' => Response::FORMAT_JSON,
                'data' => ['error' => 0, 'msg' => '设置成功'],
            ]);
        } else {
            throw new BadRequestHttpException();
        }
    }

    public function actionGetTemplateId()
    {
        $templateApi = new api\Template();
        $request = Yii::$app->getRequest();
        if ($request->isAjax && $templateIdShort = $request->post('template_id_short')) {
            $templateId = $templateApi->apiAddTemplate($templateIdShort)['template_id'];
            return new Response([
                'format' => Response::FORMAT_JSON,
                'data' => ['error' => 0, 'msg' => '模板Id:' . $templateId],
            ]);
        } else {
            throw new BadRequestHttpException();
        }
    }

    public function actionSend()
    {
        $request = Yii::$app->getRequest();
        $model = new DynamicModel(['name', 'content', 'openid']);
        $model->addRule(['name', 'content', 'openid'], 'required');
        if ($model->load($request->post()) && $model->validate()) {
            $messageApi = new api\Message;
            $post = [
                'touser' => $model->openid,
                'template_id' => 'A9WbhLYqVunlESHgjGfSuqb2VAJ4TCqSDuBJfRimmVY',
                'url' => '',
                'topcolor' => '#ff0000',
                'data' => [
                    'name' => [
                        'value' => $model->name,
                        'color' => '#ff0000',
                    ],
                    'content' => [
                        'value' => $model->content,
                        'color' => '#ff0000',
                    ]
                ]
            ];
            $messageApi->templateSend($post);
            Yii::$app->getSession()->setFlash('success', '发送模板消息成功');
            return $this->refresh();
        }

        return $this->render('send', [
            'model' => $model,
        ]);
    }
}